package net.jeanhwea.gold;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jeanhwea.gold.model.DataManager;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet implements Servlet{
  private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public void init(ServletConfig config) throws ServletException{
      System.out.println("*** initializing controller servlet. ***");
      super.init(config);
      
      DataManager dataManager = new DataManager();
      dataManager.setDbURL(config.getInitParameter("databaseURL"));
      dataManager.setDbUser(config.getInitParameter("databaseUser"));
      dataManager.setDbPasswd(config.getInitParameter("databasePasswd"));
      
      ServletContext context = config.getServletContext();
      context.setAttribute("base", config.getInitParameter("base"));
      
      try {  // load the database JDBC driver
        Class.forName(config.getInitParameter("jdbcDriver"));
      }
      catch (ClassNotFoundException e) {
        System.out.println(e.toString());
      }
    }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest req, HttpServletResponse res) 
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    doPost(req, res);
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest req, HttpServletResponse res) 
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    String base = "/gold/jsp/";
    String url = base + "index.jsp";
    String action = req.getParameter("action");
    if(action != null) {
      switch(action) {
      case "search":
        url = base + "SearchResult.jsp";
        break;
      case "show" :
        url = base + "ShowResult.jsp";
        break;
      default:
        url = base + "index.jsp";
        break;
      }
    }
    RequestDispatcher reqDispatcher = this.getServletContext().getRequestDispatcher(url);
    reqDispatcher.forward(req, res);
  }

}
